package com.jinyu.gateway.handler;

import com.jinyu.gateway.server.NettyServer;
import io.netty.buffer.ByteBuf;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.*;
import org.apache.tomcat.util.json.JSONParser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Component
@ChannelHandler.Sharable
public class HttpServerHandler extends SimpleChannelInboundHandler<FullHttpRequest> {
    @Autowired
    NettyServer nettyServer;
    private static ExecutorService executorService = null;

    static {
        executorService = Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors() * 2);
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        NettyServer.addChannel(ctx.channel());
    }

    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, FullHttpRequest fullHttpRequest) throws Exception {
//        if (fullHttpRequest.method().equals(HttpMethod.GET)) {
        HttpVersion httpVersion = fullHttpRequest.protocolVersion();
        HttpHeaders headers = fullHttpRequest.headers();
        String uri = fullHttpRequest.uri();
        ByteBuf content1 = fullHttpRequest.content();//将bytebuf转成json？
        executorService.submit(() -> {
            String content = "<html><body><h1>Hello, Netty</h1></body></html>";
            FullHttpResponse fullHttpResponse = new DefaultFullHttpResponse(fullHttpRequest.protocolVersion(),
                    HttpResponseStatus.OK);
            fullHttpResponse.content().writeBytes(content.getBytes());
            fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/html; charset=UTF-8");
            fullHttpResponse.headers().set(HttpHeaderNames.CONTENT_LENGTH, fullHttpResponse.content().readableBytes());

            channelHandlerContext.writeAndFlush(fullHttpResponse);
        });
//        }
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
